/**
 * 文档导出组件
 */

import React, { useState } from 'react';
import { Button, message, Modal, Space, Tooltip, Input, Divider } from 'antd';
import { 
  DownloadOutlined, 
  FileWordOutlined, 
  EyeOutlined,
  CopyOutlined,
  SettingOutlined
} from '@ant-design/icons';
import { formatContentToStandardHTML } from '../../../utils/document-formatter';
import { exportToWord, checkBrowserSupport } from '../../../utils/word-exporter';
import './style.css';

interface DocumentExporterProps {
  content: string;
  title?: string;
  className?: string;
}

const DocumentExporter: React.FC<DocumentExporterProps> = ({
  content,
  title = '文档',
  className
}) => {
  const [previewVisible, setPreviewVisible] = useState(false);
  const [exporting, setExporting] = useState(false);
  const [customTitle, setCustomTitle] = useState(title);
  const [settingsVisible, setSettingsVisible] = useState(false);

  // 检查浏览器支持
  const browserSupported = checkBrowserSupport();

  // 格式化内容
  const formattedHTML = formatContentToStandardHTML(content, customTitle);

  // 导出Word文档
  const handleExportWord = async () => {
    if (!browserSupported) {
      message.error('当前浏览器不支持文档下载功能');
      return;
    }

    if (!content.trim()) {
      message.warning('内容为空，无法导出');
      return;
    }

    setExporting(true);
    try {
      await exportToWord(formattedHTML, customTitle);
      message.success('Word文档下载成功');
    } catch (error) {
      console.error('导出失败:', error);
      message.error('导出失败，请重试');
    } finally {
      setExporting(false);
    }
  };

  // 预览格式化效果
  const handlePreview = () => {
    setPreviewVisible(true);
  };

  // 复制HTML内容
  const handleCopyHTML = async () => {
    try {
      await navigator.clipboard.writeText(formattedHTML);
      message.success('HTML内容已复制到剪贴板');
    } catch (error) {
      console.error('复制失败:', error);
      message.error('复制失败，请手动复制');
    }
  };

  // 打开设置
  const handleSettings = () => {
    setSettingsVisible(true);
  };

  return (
    <div className={`document-exporter ${className || ''}`}>
      <Space>
        <Button
          type="primary"
          icon={<FileWordOutlined />}
          loading={exporting}
          onClick={handleExportWord}
          disabled={!browserSupported || !content.trim()}
        >
          下载Word文档
        </Button>
        
        <Button
          icon={<EyeOutlined />}
          onClick={handlePreview}
          disabled={!content.trim()}
        >
          预览格式
        </Button>
        
        <Tooltip title="复制HTML格式">
          <Button
            icon={<CopyOutlined />}
            onClick={handleCopyHTML}
            disabled={!content.trim()}
          />
        </Tooltip>
        
        <Tooltip title="导出设置">
          <Button
            icon={<SettingOutlined />}
            onClick={handleSettings}
          />
        </Tooltip>
      </Space>

      {/* 预览模态框 */}
      <Modal
        title="格式预览"
        open={previewVisible}
        onCancel={() => setPreviewVisible(false)}
        width={900}
        footer={[
          <Button key="close" onClick={() => setPreviewVisible(false)}>
            关闭
          </Button>,
          <Button 
            key="export" 
            type="primary" 
            icon={<DownloadOutlined />}
            loading={exporting}
            onClick={handleExportWord}
          >
            导出Word
          </Button>
        ]}
      >
        <div className="document-preview">
          <div 
            className="preview-content"
            dangerouslySetInnerHTML={{ __html: formattedHTML }}
          />
        </div>
      </Modal>

      {/* 设置模态框 */}
      <Modal
        title="导出设置"
        open={settingsVisible}
        onCancel={() => setSettingsVisible(false)}
        onOk={() => setSettingsVisible(false)}
        width={500}
      >
        <div className="export-settings">
          <div className="setting-item">
            <label>文档标题：</label>
            <Input
              value={customTitle}
              onChange={(e) => setCustomTitle(e.target.value)}
              placeholder="请输入文档标题"
              maxLength={50}
            />
          </div>
          
          <Divider />
          
          <div className="format-info">
            <h4>格式说明：</h4>
            <ul>
              <li>一级标题：黑体三号，段前段后空1行，左对齐</li>
              <li>二级标题：黑体四号，段前段后空0.5行，左对齐</li>
              <li>正文：仿宋GB-2312小四号，两端对齐，首行缩进两个字符</li>
              <li>页边距：上下左右各2.54cm</li>
            </ul>
          </div>
          
          <div className="browser-info">
            <p>
              <strong>浏览器支持：</strong>
              {browserSupported ? (
                <span style={{ color: '#52c41a' }}>✓ 支持</span>
              ) : (
                <span style={{ color: '#ff4d4f' }}>✗ 不支持</span>
              )}
            </p>
            {!browserSupported && (
              <p style={{ color: '#ff4d4f', fontSize: '12px' }}>
                请使用现代浏览器（Chrome、Firefox、Safari、Edge等）
              </p>
            )}
          </div>
        </div>
      </Modal>
    </div>
  );
};

export default DocumentExporter;
